<?php
namespace app\controller;

use app\BaseController;
use app\model\User;
use app\Request;
use think\facade\Cache;


class LoginController extends BaseController{
    public function login(Request $request){
        //获取学号密码
        $param = $request->param(['password','student_id']);
        $this->validate($param,'UserValidate.login');    //新建login场景，格式验证
        $userInfo=User::where('student_id','=',$param['student_id'])->find();

        //判断是否有该用户
        if(empty($userInfo)){
                return $this->returnJson(self::USER_ERROR,'学号或密码错误');
        }

        //判断密码是否正确
        //由于数据库的密码没有进行md5加密，现在进行开发测试阶段，所以故把md5取消，开发完成会将数据进行md5加密
        if ($userInfo['password']!=$param['password']){
            return $this->returnJson(self::USER_ERROR,'学号或密码错误');
        }

        //获取到用户id并进行加密
        $uid = $userInfo['id'];
        $token = $this->signToken($uid);

        //将token存入redis并设置时长为1天
        if (!Cache::store('redis')->set($token,$userInfo,24*60*60)){
            return $this->returnJson(self::SERVER_ERROR,'服务器错误，请重试');
        }
        return $this->returnJson(self::SUCCESS,'登录成功',$token);
    }

}